<route lang="json5" type="page">
{
style: {
navigationBarTitleText: '作业完成情况',
},
}
</route>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import type { FormExpose } from 'wot-design-uni/components/wd-form/types'
import { useMessage, useToast } from 'wot-design-uni'
import dayjs from 'dayjs'
import api from '@/api'
import { useClassStore, useUserStore } from '@/store'

const store = {
  class: useClassStore(),
  user: useUserStore(),
}

const toastApi = useToast()
const messageApi = useMessage()
const form = ref<FormExpose>()

const data = reactive<{
  assignmentInfo: Awaited<ReturnType<typeof api.assignments.getAssignmentInfoByAssignmentId>>['data'] | null
  completedInfos: Awaited<ReturnType<typeof api.assignments.getCompletedInfosByAssignmentId>>['data'] | null
  incompletedInfos: Awaited<ReturnType<typeof api.assignments.getIncompletedInfosByAssignmentId>>['data'] | null
  activeTab: 'details' | 'completed' | 'incompleted'
  showEditDialog: boolean
  editorModel: {
    title: string
    description: string
    requirementType: string
    assignmentDate: number
    classIds: number[]
  }
  // 成员选择相关
  classMembers: Array<{
    userId: number
    nickname: string
    avatar: string | null
    role: string
  }>
  students: Array<{
    id: number
    nickname: string
    avatar: string | null
    className?: string // 添加班级名称，用于跨班级作业
  }>
  selectedMemberIds: number[]
  // 跨班级作业相关
  isMultiClassAssignment: boolean
  relatedClassIds: number[]
  classesData: Map<number, {
    classInfo: { id: number, name: string }
    members: Array<{
      userId: number
      nickname: string
      avatar: string | null
      role: string
    }>
    students: Array<{
      id: number
      nickname: string
      avatar: string | null
    }>
    selectedStudentIds: number[]
  }>
  // 编辑时的班级管理
  createdClasses: { value: number, label: string }[]
  currentClassId: number | null
}>({
  assignmentInfo: null,
  completedInfos: null,
  incompletedInfos: null,
  activeTab: 'details',
  showEditDialog: false,
  editorModel: {
    title: '',
    description: '',
    requirementType: '',
    assignmentDate: Date.now(),
    classIds: [],
  },
  // 成员选择相关
  classMembers: [],
  students: [],
  selectedMemberIds: [],
  // 跨班级作业相关
  isMultiClassAssignment: false,
  relatedClassIds: [],
  classesData: new Map(),
  // 编辑时的班级管理
  createdClasses: [],
  currentClassId: null,
})

// 头像错误状态管理
const avatarErrors = reactive<Record<string, boolean>>({})

// 计算属性：当前选中的成员 - 使用students数据结构
const selectedMembers = computed(() => {
  return data.students.filter(student =>
    data.selectedMemberIds.includes(student.id)
  )
})

// 编辑时的班级和学生管理方法
// 获取当前班级的学生选择状态
function getCurrentClassStudents() {
  console.log(`getCurrentClassStudents 调用 - currentClassId: ${data.currentClassId}`)
  if (!data.currentClassId) {
    console.log('getCurrentClassStudents: 没有当前班级ID')
    return []
  }

  // 始终返回当前班级的学生列表
  const classData = data.classesData.get(data.currentClassId)
  console.log(`getCurrentClassStudents: 班级 ${data.currentClassId} 的数据:`, classData)
  const students = classData?.students || []
  console.log(`getCurrentClassStudents: 返回学生数量: ${students.length}`, students)
  return students
}

function getCurrentClassSelectedIds() {
  if (!data.currentClassId) return []
  const classData = data.classesData.get(data.currentClassId)
  return classData?.selectedStudentIds || []
}

// 计算属性：当前班级是否全选了所有学生（编辑模式）
const isCurrentClassAllSelected = computed(() => {
  const currentStudents = getCurrentClassStudents()
  const selectedIds = getCurrentClassSelectedIds()
  return currentStudents.length > 0 && selectedIds.length === currentStudents.length
})

// 处理全选/取消全选学生（当前班级，编辑模式）
function handleSelectAllCurrentClassStudents() {
  if (!data.currentClassId) return

  const classData = data.classesData.get(data.currentClassId)
  if (!classData) return

  if (isCurrentClassAllSelected.value) {
    // 取消全选：对当前班级的每个学生调用取消选择
    classData.students.forEach(student => {
      setStudentChecked(student.id, false)
    })
  } else {
    // 全选：对当前班级的每个学生调用选择
    classData.students.forEach(student => {
      setStudentChecked(student.id, true)
    })
  }
}

// 设置学生选中状态（同步所有班级）
function setStudentChecked(studentId: number, event: any) {
  // 处理 wot-design-uni checkbox 的事件对象
  const isChecked = event === true || event?.detail?.value === true || event?.value === true

  // 同步更新所有包含该学生的班级
  data.classesData.forEach((classData) => {
    // 检查该班级是否包含这个学生
    const hasStudent = classData.students.some(student => student.id === studentId)
    if (!hasStudent) return

    if (isChecked) {
      // 选中：如果该学生不在选中列表中，则添加
      if (!classData.selectedStudentIds.includes(studentId)) {
        classData.selectedStudentIds.push(studentId)
      }
    } else {
      // 取消选中：从选中列表中移除
      const index = classData.selectedStudentIds.indexOf(studentId)
      if (index > -1) {
        classData.selectedStudentIds.splice(index, 1)
      }
    }
  })

  // 更新全局选中的成员ID列表
  updateSelectedMemberIds()
}

// 获取学生选中状态（检查所有班级）
function getStudentChecked(studentId: number) {
  // 检查该学生是否在任何班级中被选中
  let isSelected = false
  data.classesData.forEach((classData) => {
    if (classData.selectedStudentIds.includes(studentId)) {
      isSelected = true
    }
  })
  return isSelected
}

// 获取所有班级选中的学生ID（去重）
function getAllSelectedStudentIds() {
  const allSelectedIds: number[] = []
  data.classesData.forEach((classData) => {
    allSelectedIds.push(...classData.selectedStudentIds)
  })
  // 使用Set去除重复的学生ID
  return Array.from(new Set(allSelectedIds))
}

// 获取所有班级选中的学生总数
function getTotalSelectedStudentsCount() {
  return getAllSelectedStudentIds().length
}

// 获取所有班级的学生总数（去重）
function getTotalStudentsCount() {
  const allStudentIds: number[] = []

  // 收集所有班级的学生ID
  data.classesData.forEach((classData) => {
    classData.students.forEach(student => {
      allStudentIds.push(student.id)
    })
  })

  // 使用Set去除重复的学生ID，返回去重后的总数
  return Array.from(new Set(allStudentIds)).length
}

// 切换到指定班级
function switchToClass(classId: number) {
  console.log(`switchToClass 被调用，目标班级: ${classId}`)
  console.log('当前editorModel.classIds:', data.editorModel.classIds)
  console.log('当前classesData keys:', Array.from(data.classesData.keys()))

  // 如果班级数据不存在，尝试加载
  if (!data.classesData.has(classId)) {
    console.log(`班级 ${classId} 数据不存在，尝试加载`)
    loadClassMembersForEdit(classId).then(() => {
      console.log(`班级 ${classId} 数据加载完成，重新切换`)
      // 重新执行切换逻辑
      const classData = data.classesData.get(classId)
      if (classData) {
        data.students = classData.students
        console.log(`延迟切换到班级 ${classId}，学生数: ${data.students.length}`)
      }
    }).catch(error => {
      console.error(`班级 ${classId} 数据加载失败:`, error)
    })
  }

  data.currentClassId = classId
  const classData = data.classesData.get(classId)
  console.log(`班级 ${classId} 的数据:`, classData)
  if (classData) {
    // 始终更新为当前班级的学生列表
    data.students = classData.students
    console.log(`切换到班级 ${classId}，学生数: ${data.students.length}`, data.students)
  } else {
    data.students = []
    console.log(`班级 ${classId} 数据不存在，设置空学生列表`)
  }
  console.log(`switchToClass 完成，当前状态:`)
  console.log('- currentClassId:', data.currentClassId)
  console.log('- students count:', data.students.length)
}

// 获取班级显示名称
function getClassDisplayName(classId: number) {
  const classData = data.classesData.get(classId)
  if (classData?.classInfo?.name) {
    return classData.classInfo.name
  }

  // 尝试从创建的班级列表中获取名称
  const createdClass = data.createdClasses.find(cls => cls.value === classId)
  if (createdClass?.label) {
    return createdClass.label
  }

  console.warn(`无法获取班级 ${classId} 的名称，classData:`, classData)
  return `班级${classId}`
}

// 获取班级选中学生数量
function getClassSelectedCount(classId: number) {
  const classData = data.classesData.get(classId)
  return classData?.selectedStudentIds.length || 0
}

// 获取班级学生总数
function getClassStudentCount(classId: number) {
  const classData = data.classesData.get(classId)
  return classData?.students.length || 0
}



// 加载用户创建的班级列表
async function loadCreatedClasses() {
  try {
    const { data: classes } = await api.classes.getClassesByCurrentUser()
    // 过滤出用户创建的班级（role为teacher）
    const createdClasses = classes.filter(cls => cls.role === 'teacher')
    data.createdClasses = createdClasses.map(cls => ({
      value: cls.id,
      label: cls.className
    }))
  } catch (error) {
    console.error('加载班级列表失败:', error)
    toastApi.error('加载班级列表失败')
  }
}

// 加载班级成员（编辑模式）
async function loadClassMembersForEdit(classId: number) {
  try {
    console.log(`开始加载班级 ${classId} 的成员信息`)

    const { data: classInfo } = await api.classes.getClassInfoByClassId(classId)
    // 临时使用getMembersByClassId来调试问题
    const { data: allMembers } = await api.classes.getMembersByClassId(classId)
    console.log(`班级 ${classId} 所有成员:`, allMembers)

    // 过滤出学生（排除老师）
    const students = allMembers.filter(member => member.role !== 'teacher')
    console.log(`班级 ${classId} 过滤后的学生:`, students)

    console.log(`班级 ${classId} 信息:`, classInfo)

    // 确保班级名称存在
    const className = classInfo?.className || `班级${classId}`

    // 检查学生数据是否为数组
    if (!Array.isArray(students)) {
      console.error(`班级 ${classId} 学生数据不是数组:`, students)
      throw new Error(`班级 ${classId} 学生数据格式错误`)
    }

    // 转换学生数据格式
    const studentList = students.map(student => ({
      id: student.userId,
      nickname: student.nickname,
      avatar: student.avatar,
    }))

    console.log(`班级 ${classId} 转换后的学生数据:`, studentList)

    // 存储班级数据
    data.classesData.set(classId, {
      classInfo: { id: classId, name: className },
      members: students, // 保存原始成员数据
      students: studentList,
      selectedStudentIds: []
    })

    console.log(`班级 ${classId} (${className}) 学生加载完成，学生数: ${studentList.length}`)
    console.log(`存储的班级数据:`, data.classesData.get(classId))
  } catch (error) {
    console.error(`加载班级 ${classId} 成员失败:`, error)
    console.error('错误详情:', {
      message: error.message,
      stack: error.stack,
      response: error.response
    })
    toastApi.error(`加载班级 ${classId} 成员失败: ${error.message}`)

    // 即使加载失败，也要存储基本信息以避免显示错误
    const fallbackName = data.createdClasses.find(cls => cls.value === classId)?.label || `班级${classId}`
    console.log(`为班级 ${classId} 设置fallback数据:`, fallbackName)
    data.classesData.set(classId, {
      classInfo: { id: classId, name: fallbackName },
      members: [],
      students: [],
      selectedStudentIds: []
    })
    console.log(`班级 ${classId} fallback数据设置完成`)
  }
}

// 监听班级选择变化（编辑模式）
async function handleEditClassChange() {
  console.log('handleEditClassChange 开始，选中的班级:', data.editorModel.classIds)
  console.log('当前已加载的班级数据:', Array.from(data.classesData.keys()))

  // 加载所有选中班级的成员
  for (const classId of data.editorModel.classIds) {
    console.log(`检查班级 ${classId} 是否需要加载数据`)
    if (!data.classesData.has(classId)) {
      console.log(`班级 ${classId} 数据不存在，开始加载`)
      try {
        await loadClassMembersForEdit(classId)
        console.log(`班级 ${classId} 数据加载完成`)
      } catch (error) {
        console.error(`班级 ${classId} 数据加载失败:`, error)
      }
    } else {
      console.log(`班级 ${classId} 数据已存在，跳过加载`)
    }
  }

  // 移除未选中班级的数据
  const classIdsToDelete: number[] = []
  data.classesData.forEach((_, classId) => {
    if (!data.editorModel.classIds.includes(classId)) {
      classIdsToDelete.push(classId)
    }
  })
  classIdsToDelete.forEach(classId => data.classesData.delete(classId))

  // 设置当前显示的班级（第一个选中的班级）
  console.log('设置当前显示班级，选中的班级:', data.editorModel.classIds)
  if (data.editorModel.classIds.length > 0) {
    const targetClassId = data.editorModel.classIds[0]
    console.log(`设置当前班级为: ${targetClassId}`)
    data.currentClassId = targetClassId
    console.log('调用switchToClass前，classesData状态:', Array.from(data.classesData.keys()))
    switchToClass(data.currentClassId)
  } else {
    console.log('没有选中的班级，清空当前班级')
    data.currentClassId = null
    data.students = []
  }

  console.log('handleEditClassChange 完成，最终状态:')
  console.log('- currentClassId:', data.currentClassId)
  console.log('- classesData keys:', Array.from(data.classesData.keys()))
  console.log('- 当前班级数据:', data.classesData.get(data.currentClassId))

  // 重新计算选中的成员
  updateSelectedMemberIds()
}

// 更新选中的成员ID列表
function updateSelectedMemberIds() {
  data.selectedMemberIds = getAllSelectedStudentIds()
}



const isCreator = computed(() => {
  // 确保数据已加载
  if (!data.assignmentInfo || !store.user.userInfo) {
    return false
  }

  // 统一转换为字符串进行比较，确保数据类型一致
  const creatorId = String(data.assignmentInfo.creatorId)
  const currentUserId = String(store.user.userInfo.id)

  return creatorId === currentUserId
})

// 存储作业ID
let assignmentId: number = 0

// 加载作业数据
async function loadAssignmentData() {
  if (Number.isNaN(assignmentId)) {
    await uni.navigateBack()
    return
  }

  try {
    // 重置头像错误状态
    Object.keys(avatarErrors).forEach(key => {
      delete avatarErrors[key]
    })

    data.assignmentInfo = (await api.assignments.getAssignmentInfoByAssignmentId(assignmentId)).data
    data.completedInfos = (await api.assignments.getCompletedInfosByAssignmentId(assignmentId)).data
    data.incompletedInfos = (await api.assignments.getIncompletedInfosByAssignmentId(assignmentId)).data

    // 调试信息
    console.log('📊 作业数据加载完成:', {
      作业ID: assignmentId,
      作业标题: data.assignmentInfo.title,
      总绘本数: data.assignmentInfo.totalBooks,
      完成人数统计: data.assignmentInfo.completedCount,
      总成员数: data.assignmentInfo.totalMembers,
      已完成列表长度: data.completedInfos?.length || 0,
      未完成列表长度: data.incompletedInfos?.length || 0,
      已完成列表数据: data.completedInfos,
      未完成列表数据: data.incompletedInfos
    })
    data.editorModel.title = data.assignmentInfo.title
    data.editorModel.description = data.assignmentInfo.description
    data.editorModel.requirementType = data.assignmentInfo.requirementType
    data.editorModel.assignmentDate = new Date(data.assignmentInfo.assignmentDate).getTime()

    // 检查是否为跨班级作业并加载相关班级成员
    await loadAssignmentMembers()

    // 调试日志：显示绘本完成状态
    console.log('📚 作业绘本完成状态:', data.assignmentInfo.books?.map(book => ({
      id: book.id,
      title: book.title,
      isCompleted: book.isCompleted
    })))
  } catch (error) {
    console.error('加载作业数据失败:', error)
    toastApi.error('加载数据失败，请重试')
  }
}

onLoad(async (query) => {
  assignmentId = Number.parseInt(query.assignmentId)
  console.log('作业详情页面加载，作业ID:', assignmentId)
  await loadAssignmentData()
})

// 页面显示时刷新数据（从阅读页面返回时会触发）
onShow(async () => {
  if (assignmentId) {
    console.log('作业详情页面显示，刷新数据')
    await loadAssignmentData()
  }
})

const validators = {
  validateTitle: (title: string) => {
    if (title.trim().length > 0) {
      return Promise.resolve()
    }
    else {
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('作业名称不可为空')
    }
  },
  validateDescription: (description: string) => {
    if (description.trim().length > 0) {
      return Promise.resolve()
    }
    else {
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('作业描述不可为空')
    }
  },
}

async function deleteAssignment() {
  try {
    await messageApi.confirm({
      title: '提示',
      msg: '确认要删除作业吗？',
    })

    const { code, data: successMsg, msg } = await api.assignments.deleteAssignmentByAssignmentId(data.assignmentInfo.id)

    if (code === 0) {
      toastApi.success({
        msg: successMsg,
        duration: 1500,
        closed: () => {
          store.class.setRefresh(true)
          uni.navigateBack()
        },
      })
    }
    else {
      toastApi.error({
        msg,
        duration: 1500,
      })
    }
  }
  catch (_) {

  }
}

// 编辑作业
async function editAssignment() {
  if (data.assignmentInfo) {
    // 加载班级列表
    await loadCreatedClasses()

    data.editorModel.title = data.assignmentInfo.title
    data.editorModel.description = data.assignmentInfo.description || ''
    data.editorModel.requirementType = data.assignmentInfo.requirementType
    data.editorModel.assignmentDate = new Date(data.assignmentInfo.assignmentDate).getTime()

    // 初始化班级选择
    console.log('编辑作业初始化 - 作业信息:', {
      isMultiClassAssignment: data.isMultiClassAssignment,
      relatedClassIds: data.relatedClassIds,
      assignmentClassId: data.assignmentInfo.classId
    })

    if (data.isMultiClassAssignment) {
      data.editorModel.classIds = [...data.relatedClassIds]
      console.log('多班级作业，设置班级IDs:', data.editorModel.classIds)
    } else {
      data.editorModel.classIds = data.assignmentInfo.classId ? [data.assignmentInfo.classId] : []
      console.log('单班级作业，设置班级IDs:', data.editorModel.classIds)
    }

    // 加载选中班级的成员数据
    console.log('准备调用handleEditClassChange，班级IDs:', data.editorModel.classIds)
    await handleEditClassChange()
    console.log('handleEditClassChange 调用完成')

    // 初始化当前作业的参与成员
    const currentParticipants = []
    if (data.completedInfos) {
      currentParticipants.push(...data.completedInfos.map(info => info.userId))
    }
    if (data.incompletedInfos) {
      currentParticipants.push(...data.incompletedInfos.map(info => info.userId))
    }

    // 在各个班级中标记已选中的学生
    data.classesData.forEach((classData) => {
      classData.selectedStudentIds = classData.students
        .filter(student => currentParticipants.includes(student.id))
        .map(student => student.id)
    })

    // 更新选中的成员ID列表
    updateSelectedMemberIds()

    console.log('编辑作业初始化:', {
      作业类型: data.isMultiClassAssignment ? '跨班级' : '单班级',
      涉及班级: data.editorModel.classIds,
      可选学生数: getTotalStudentsCount(),
      当前参与成员: data.selectedMemberIds.length
    })
  }
  data.showEditDialog = true
}

// 保存编辑
async function handleSaveEdit() {
  try {
    // 验证班级选择
    if (data.editorModel.classIds.length === 0) {
      toastApi.error('请至少选择一个班级')
      return
    }

    // 验证成员选择
    const allSelectedIds = getAllSelectedStudentIds()
    if (allSelectedIds.length === 0) {
      toastApi.error('请至少选择一名学生参与作业')
      return
    }

    const { valid } = await form.value.validate()
    if (valid) {
      // 准备更新数据，包含成员信息和截止日期
      const updateData = {
        title: data.editorModel.title,
        description: data.editorModel.description,
        requirementType: data.editorModel.requirementType,
        assignmentDate: dayjs(data.editorModel.assignmentDate).format('YYYY-MM-DD'),
        participantMemberIds: allSelectedIds
      }

      const {
        code,
        data: successMsg,
        msg,
      } = await api.assignments.editAssignmentByAssignmentId(data.assignmentInfo.id, updateData)

      if (code === 0) {
        data.assignmentInfo.title = data.editorModel.title
        data.assignmentInfo.description = data.editorModel.description
        data.assignmentInfo.requirementType = data.editorModel.requirementType
        data.assignmentInfo.assignmentDate = dayjs(data.editorModel.assignmentDate).format('YYYY-MM-DD')

        // 检查是否有成员变更
        const originalMemberCount = (data.completedInfos?.length || 0) + (data.incompletedInfos?.length || 0)
        const newMemberCount = allSelectedIds.length
        const memberChanged = newMemberCount !== originalMemberCount

        let message = successMsg
        if (memberChanged) {
          message += `\n参与成员已更新：${newMemberCount}人`
        }

        toastApi.success({
          msg: message,
          duration: 2000,
        })
        data.showEditDialog = false

        // 重新加载数据以反映成员变更
        await loadAssignmentData()

        console.log('作业编辑保存完成，数据已刷新')
      }
      else {
        toastApi.error({
          msg,
          duration: 1500,
        })
      }
    }
  }
  catch (error) {
    console.error('保存失败:', error)
    toastApi.error({
      msg: '保存失败，请重试',
      duration: 1500,
    })
  }
}

// 打开绘本图片集
function openPictureBook(book: any) {
  // 跳转到绘本阅读页面，传递作业相关参数
  const params = [
    `bookId=${book.id}`,
    `title=${encodeURIComponent(book.title)}`,
    `assignmentId=${data.assignmentInfo?.id || ''}`,
    `requirementType=${data.assignmentInfo?.requirementType || ''}`,
    `fromAssignment=true`,
    `isTeacher=${isCreator.value}` // 传递老师标识
  ].join('&')

  uni.navigateTo({
    url: `/pages-sub/reading/picture-book-reader/index?${params}`,
  })
}

// 格式化日期时间
function formatDateTime(dateTime: string) {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (days === 0) {
    return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  } else if (days === 1) {
    return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return `${date.getMonth() + 1}/${date.getDate()}`
  }
}

// 获取状态样式类
function getStatusClass(status: string) {
  switch (status) {
    case '已完成':
      return 'completed'
    case '进行中':
      return 'in-progress'
    case '未开始':
      return 'not-started'
    default:
      return 'unknown'
  }
}

// 加载作业相关的成员信息（支持单班级和跨班级作业）
async function loadAssignmentMembers() {
  try {
    // 只有作业创建者才需要加载班级成员信息（用于编辑作业）
    if (!isCreator.value) {
      console.log('当前用户不是作业创建者，跳过加载班级成员信息')
      return
    }

    // 检查是否为跨班级作业（classId为null表示跨班级作业）
    if (data.assignmentInfo?.classId === null) {
      // 跨班级作业：获取关联的班级列表
      data.isMultiClassAssignment = true
      const { data: relatedClasses } = await api.assignments.getAssignmentClasses(data.assignmentInfo.id)
      data.relatedClassIds = relatedClasses.map(cls => cls.classId)

      // 加载所有相关班级的成员
      await loadMultiClassMembers(data.relatedClassIds)
    } else if (data.assignmentInfo?.classId) {
      // 单班级作业：加载单个班级的成员
      data.isMultiClassAssignment = false
      data.relatedClassIds = [data.assignmentInfo.classId]
      await loadSingleClassMembers(data.assignmentInfo.classId)
    }

    // 初始化当前参与作业的成员
    initializeSelectedMembers()
  } catch (error) {
    console.error('加载作业成员失败:', error)
    toastApi.error('加载作业成员失败')
  }
}

// 加载单班级成员
async function loadSingleClassMembers(classId: number) {
  try {
    // 使用专门的学生API，直接获取学生成员（排除老师）
    const { data: students } = await api.classes.getStudentsByClassId(classId)

    // 保存原始成员数据（用于兼容性）
    data.classMembers = students.map(student => ({
      userId: student.userId,
      nickname: student.nickname,
      avatar: student.avatar,
      role: student.role
    }))

    // 转换为学生数据格式
    data.students = students.map(student => ({
      id: student.userId,
      nickname: student.nickname,
      avatar: student.avatar,
    }))

    console.log('单班级成员加载完成:', {
      班级ID: classId,
      总成员: data.classMembers.length,
      学生数量: data.students.length
    })
  } catch (error) {
    console.error('加载单班级成员失败:', error)
    throw error
  }
}

// 加载多班级成员
async function loadMultiClassMembers(classIds: number[]) {
  try {
    data.classesData.clear()
    const allStudents: any[] = []
    const allMembers: any[] = []

    for (const classId of classIds) {
      // 获取班级信息
      const { data: classInfo } = await api.classes.getClassInfoByClassId(classId)

      // 使用专门的学生API，直接获取学生成员（排除老师）
      const { data: students } = await api.classes.getStudentsByClassId(classId)

      // 转换学生数据格式
      const studentList = students.map(student => ({
        id: student.userId,
        nickname: student.nickname,
        avatar: student.avatar,
        className: classInfo.className // 添加班级名称
      }))

      // 存储班级数据
      data.classesData.set(classId, {
        classInfo: { id: classInfo.id, name: classInfo.className },
        members: students, // 保存原始学生数据
        students: studentList,
        selectedStudentIds: []
      })

      // 合并到总列表
      allMembers.push(...students.map(student => ({
        userId: student.userId,
        nickname: student.nickname,
        avatar: student.avatar,
        role: student.role
      })))

      allStudents.push(...studentList)
    }

    // 去重（同一学生可能在多个班级）
    const uniqueStudents = allStudents.filter((student, index, self) =>
      index === self.findIndex(s => s.id === student.id)
    )

    const uniqueMembers = allMembers.filter((member, index, self) =>
      index === self.findIndex(m => m.userId === member.userId)
    )

    data.students = uniqueStudents
    data.classMembers = uniqueMembers

    console.log('跨班级成员加载完成:', {
      涉及班级: classIds.length,
      总成员: data.classMembers.length,
      学生数量: data.students.length,
      班级详情: Array.from(data.classesData.entries()).map(([classId, classData]) => ({
        班级ID: classId,
        班级名称: classData.classInfo.name,
        学生数: classData.students.length
      }))
    })
  } catch (error) {
    console.error('加载跨班级成员失败:', error)
    throw error
  }
}

// 初始化选中的成员
function initializeSelectedMembers() {
  const currentParticipants = new Set<number>()

  // 从已完成和未完成列表中收集当前参与的成员ID
  if (data.completedInfos) {
    data.completedInfos.forEach(info => currentParticipants.add(info.userId))
  }
  if (data.incompletedInfos) {
    data.incompletedInfos.forEach(info => currentParticipants.add(info.userId))
  }

  data.selectedMemberIds = Array.from(currentParticipants)

  // 同步更新各个班级的选择状态
  data.classesData.forEach((classData) => {
    classData.selectedStudentIds = classData.students
      .filter(student => currentParticipants.has(student.id))
      .map(student => student.id)
  })

  console.log('参与成员初始化完成:', {
    当前参与成员: data.selectedMemberIds.length,
    作业类型: data.isMultiClassAssignment ? '跨班级' : '单班级',
    各班级选择状态: Array.from(data.classesData.entries()).map(([classId, classData]) => ({
      班级ID: classId,
      选中学生数: classData.selectedStudentIds.length,
      总学生数: classData.students.length
    }))
  })
}

// 头像错误处理
function handleAvatarError(key: string) {
  console.log('头像加载失败:', key)
  avatarErrors[key] = true
}

// 获取头像文本（昵称首字符）
function getAvatarText(nickname: string) {
  if (!nickname) return '?'
  // 获取第一个字符，如果是emoji或特殊字符，取前两个字符
  const firstChar = nickname.charAt(0)
  // 检查是否是中文、英文或数字
  if (/[\u4e00-\u9fa5a-zA-Z0-9]/.test(firstChar)) {
    return firstChar.toUpperCase()
  }
  // 如果是特殊字符，尝试取前两个字符或使用默认
  return nickname.length > 1 ? nickname.substring(0, 2) : '?'
}

// 获取完成要求文本
function getRequirementText(requirementType: string) {
  switch (requirementType) {
    case 'read':
      return '完成阅读'
    case 'audio':
      return '完成配音'
    default:
      return '完成作业'
  }
}

// 获取绘本完成状态文本
function getBookCompletionText(isCompleted: boolean, requirementType: string) {
  // 如果是老师（创建者），显示不同的文本
  if (isCreator.value) {
    switch (requirementType) {
      case 'read':
        return '阅读绘本'
      case 'audio':
        return '配音绘本'
      default:
        return '作业绘本'
    }
  }

  // 学生的状态文本
  if (isCompleted) {
    switch (requirementType) {
      case 'read':
        return '已阅读'
      case 'audio':
        return '已配音'
      default:
        return '已完成'
    }
  } else {
    switch (requirementType) {
      case 'read':
        return '待阅读'
      case 'audio':
        return '待配音'
      default:
        return '待完成'
    }
  }
}


</script>

<template>
  <view class="root-container">
    <!-- 编辑作业弹窗 -->
    <wd-popup
      v-model="data.showEditDialog"
      position="bottom"
      :safe-area-inset-bottom="true"
      custom-class="edit-popup"
    >
      <view class="edit-dialog">
        <view class="dialog-header">
          <view class="header-left">
            <text class="dialog-title">编辑作业</text>
            <text v-if="data.isMultiClassAssignment" class="assignment-type-badge">跨班级作业</text>
          </view>
          <wd-button
            type="text"
            icon="close"
            size="small"
            @click="data.showEditDialog = false"
          />
        </view>

        <view class="dialog-content">
          <wd-form ref="form" :model="data.editorModel">
            <view class="form-container">
              <view class="form-item">
                <text class="form-label">作业名称：</text>
                <wd-input
                  v-model="data.editorModel.title"
                  prop="title"
                  placeholder="请输入作业名称……"
                  :rules="[{ required: false, validator: validators.validateTitle, message: '' }]"
                  clearable
                  custom-class="form-input"
                />
              </view>

              <view class="form-item">
                <text class="form-label">作业描述：</text>
                <wd-input
                  v-model="data.editorModel.description"
                  prop="description"
                  placeholder="请输入作业描述……"
                  :rules="[{ required: false, validator: validators.validateDescription, message: '' }]"
                  clearable
                  custom-class="form-input"
                />
              </view>

              <view class="form-item">
                <text class="form-label">完成条件：</text>
                <wd-picker
                  v-model="data.editorModel.requirementType"
                  prop="requirementType"
                  :columns="[{ label: `完成配音`, value: `audio` }, { label: `完成阅读`, value: `read` }]"
                  custom-class="form-input"
                />
              </view>

              <view class="form-item">
                <text class="form-label">截止日期：</text>
                <wd-calendar
                  v-model="data.editorModel.assignmentDate"
                  prop="assignmentDate"
                  placeholder="请选择截止日期……"
                  custom-class="form-input"
                />
              </view>

              <!-- 班级选择 -->
              <view class="form-item">
                <text class="form-label">作业班级：</text>
                <wd-select-picker
                  v-model="data.editorModel.classIds"
                  prop="classIds"
                  :columns="data.createdClasses"
                  placeholder="请选择作业班级……"
                  custom-class="form-input"
                  @change="handleEditClassChange"
                />
              </view>

              <!-- 成员选择 -->
              <view v-if="data.editorModel.classIds.length > 0" class="form-item">
                <view class="form-label-row">
                  <text class="form-label">参与成员：</text>
                  <text class="member-count">已选{{ getTotalSelectedStudentsCount() }}/{{ getTotalStudentsCount() }}人</text>
                </view>

                <!-- 多班级学生选择 -->
                <view v-if="data.editorModel.classIds.length > 0" class="member-preview">
                  <!-- 班级切换标签 -->
                  <view v-if="data.editorModel.classIds.length > 1" class="class-tabs">
                    <view
                      v-for="classId in data.editorModel.classIds"
                      :key="classId"
                      class="class-tab"
                      :class="{ active: data.currentClassId === classId }"
                      @click="switchToClass(classId)"
                    >
                      <text class="tab-text">{{ getClassDisplayName(classId) }}</text>
                      <text class="tab-count">({{ getClassSelectedCount(classId) }}/{{ getClassStudentCount(classId) }})</text>
                    </view>
                  </view>

                  <!-- 当前班级的学生选择 -->
                  <view v-if="data.currentClassId" class="current-class-students">
                    <view class="class-header">
                      <wd-button
                        :type="isCurrentClassAllSelected ? 'warning' : 'primary'"
                        size="small"
                        plain
                        round
                        @click="handleSelectAllCurrentClassStudents"
                      >
                        {{ isCurrentClassAllSelected ? '取消全选' : '全选' }}
                      </wd-button>
                    </view>

                    <view v-if="getCurrentClassStudents().length > 0" class="student-container">
                      <scroll-view
                        class="student-scroll"
                        scroll-y
                        :show-scrollbar="false"
                        :enable-flex="true"
                      >
                        <view class="student-list">
                          <view
                            v-for="student in getCurrentClassStudents()"
                            :key="student.id"
                            class="student-item"
                          >
                            <wd-checkbox
                              :model-value="getStudentChecked(student.id)"
                              @update:model-value="(checked: boolean) => setStudentChecked(student.id, checked)"
                            >
                              <view class="student-content">
                                <view class="student-avatar">
                                  <wd-img
                                    v-if="student.avatar && !avatarErrors[`edit-${student.id}`]"
                                    :src="student.avatar"
                                    width="32px"
                                    height="32px"
                                    shape="circle"
                                    @error="handleAvatarError(`edit-${student.id}`)"
                                  />
                                  <view v-else class="avatar-placeholder">
                                    {{ getAvatarText(student.nickname) }}
                                  </view>
                                </view>
                                <text class="student-name">{{ student.nickname }}</text>
                              </view>
                            </wd-checkbox>
                          </view>
                        </view>
                      </scroll-view>
                    </view>

                    <view v-else class="no-students">
                      <wd-icon name="warning" size="20px" color="#ff4d4f" />
                      <text class="no-students-text">该班级没有学生</text>
                    </view>
                  </view>
                </view>

                <view v-else class="no-students">
                  <wd-icon name="warning" size="20px" color="#ff4d4f" />
                  <text class="no-students-text">请先选择班级</text>
                </view>
              </view>
            </view>
          </wd-form>
        </view>

        <view class="dialog-footer">
          <wd-button
            type="default"
            size="large"
            custom-class="cancel-btn"
            @click="data.showEditDialog = false"
          >
            取消
          </wd-button>
          <wd-button
            type="primary"
            size="large"
            custom-class="confirm-btn"
            @click="handleSaveEdit"
          >
            保存
          </wd-button>
        </view>
      </view>
    </wd-popup>



    <wd-message-box />
    <wd-toast />

    <!-- 内容包装器 -->
    <view class="content-wrapper">
      <wd-card
        v-if="data.assignmentInfo !== null && data.completedInfos !== null && data.incompletedInfos !== null"
        custom-class="assignment-card"
      >
      <view class="card-content">
        <view class="left-icon-area">
          <wd-icon name="spool" size="22px" color="#ffffff" />
        </view>

        <view class="middle-info-area">
          <text class="assignment-title">
            {{ data.assignmentInfo.title }}
          </text>

          <view class="assignment-details">
            <view class="detail-row">
              <view class="detail-item">
                <wd-icon name="check-circle" size="14px" color="#1890ff" />
                <text class="detail-label">完成条件：</text>
                <text class="detail-text">{{ getRequirementText(data.assignmentInfo.requirementType) }}</text>
              </view>
              <view class="detail-item">
                <wd-icon name="books" size="14px" color="#52c41a" />
                <text class="detail-label">绘本数量：</text>
                <text class="detail-text">{{ data.assignmentInfo.totalBooks }} 本</text>
              </view>
            </view>

            <view class="detail-row">
              <view class="detail-item">
                <wd-icon name="history" size="14px" color="#ff6b6b" />
                <text class="detail-label">截止日期：</text>
                <text class="detail-text">{{ dayjs(data.assignmentInfo.assignmentDate).format('YYYY年MM月DD日') }}</text>
              </view>
            </view>

            <view class="progress-section">
              <view class="progress-info">
                <wd-icon name="chart" size="14px" color="#faad14" />
                <text class="detail-label">完成人数：</text>
                <text class="progress-text">{{ data.assignmentInfo.completedCount }}/{{ data.assignmentInfo.totalMembers }} 人</text>
              </view>
              <view class="progress-bar">
                <view
                  class="progress-fill"
                  :style="{ width: `${(data.assignmentInfo.completedCount / data.assignmentInfo.totalMembers * 100)}%` }"
                ></view>
              </view>
            </view>
          </view>
        </view>

        <view v-if="isCreator" class="right-actions-area-horizontal">
          <wd-button type="icon" size="small" icon="edit-outline" @click="editAssignment()" />
          <wd-button type="icon" size="small" icon="delete-thin" @click="deleteAssignment()" />
        </view>
      </view>
    </wd-card>

    <view
      v-if="data.assignmentInfo !== null && data.completedInfos !== null && data.incompletedInfos !== null"
      class="tabs-container"
    >
      <wd-tabs v-model="data.activeTab" :scroll="false">
        <wd-tab title="作业详情" name="details" />
        <wd-tab :title="`已完成 (${data.completedInfos.length}人)`" name="completed" />
        <wd-tab :title="`未完成 (${data.incompletedInfos.length}人)`" name="incompleted" />
      </wd-tabs>

      <view class="tab-content">
        <view v-if="data.activeTab === 'details'" class="detail-tab-content">
          <!-- 绘本列表 -->
          <view class="books-section">
            <!-- <view class="section-header"> -->
              <!-- <wd-icon name="book" size="18px" color="#1890ff" /> -->
              <!-- <text class="section-title">作业绘本</text> -->
            <!-- </view> -->
            <view v-if="data.assignmentInfo?.books && data.assignmentInfo.books.length > 0" class="books-grid">
              <view
                v-for="book in data.assignmentInfo.books"
                :key="book.id"
                class="book-detail-card"
                @click="openPictureBook(book)"
              >
                <view class="book-header">
                  <view class="book-cover-container">
                    <image class="book-cover" :src="book.cover" mode="aspectFill" />
                    <!-- <view class="book-index">{{ index + 1 }}</view> -->
                    <view class="completion-badge" :class="{ completed: book.isCompleted }">
                      <wd-icon
                        :name="isCreator ? 'book' : (book.isCompleted ? 'check-circle' : 'time-circle')"
                        size="16px"
                        :color="isCreator ? '#1890ff' : (book.isCompleted ? '#52c41a' : '#faad14')"
                      />
                    </view>
                    <!-- 完成遮罩 - 老师不显示 -->
                    <view v-if="book.isCompleted && !isCreator" class="completion-overlay">
                      <wd-icon name="check-circle" size="24px" color="#52c41a" />
                      <text class="completion-text">{{ getBookCompletionText(true, data.assignmentInfo.requirementType) }}</text>
                    </view>
                  </view>
                </view>

                <view class="book-content">
                  <text class="book-title">{{ book.title }}</text>

                  <view class="book-meta">
                    <view class="meta-item">
                      <wd-icon
                        :name="isCreator ? 'book' : (book.isCompleted ? 'check-circle' : 'clock')"
                        size="12px"
                        :color="isCreator ? '#1890ff' : (book.isCompleted ? '#52c41a' : '#ff4d4f')"
                      />
                      <text class="meta-text" :class="{ completed: book.isCompleted }">
                        {{ getBookCompletionText(book.isCompleted, data.assignmentInfo.requirementType) }}
                      </text>
                    </view>
                  </view>

                  <view class="book-actions">
                    <view class="action-button primary">
                      <wd-icon
                        name="play"
                        size="14px"
                        color="#fff"
                      />
                      <text class="action-text">
                        {{ data.assignmentInfo.requirementType === 'audio' ? '开始配音' : '开始阅读' }}
                      </text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view v-else class="empty-state">
              <wd-icon name="warning" size="48px" color="#bbb" />
              <text class="empty-title">暂无绘本</text>
              <text class="empty-desc">该作业还没有添加绘本</text>
            </view>
          </view>
        </view>

        <view v-if="data.activeTab === 'completed'" class="member-list-tab-content">
          <view v-if="data.completedInfos.length > 0">
            <view
              v-for="item in data.completedInfos"
              :key="item.userId"
              class="member-detail-card"
              @click="() => {}"
            >
              <view class="member-header">
                <view class="avatar-container">
                  <wd-img
                    v-if="item.avatar && !avatarErrors[`completed-${item.userId}`]"
                    :src="item.avatar"
                    width="44px"
                    height="44px"
                    shape="circle"
                    custom-class="member-avatar"
                    @error="handleAvatarError(`completed-${item.userId}`)"
                  />
                  <view v-else class="member-avatar-placeholder">
                    {{ getAvatarText(item.nickname) }}
                  </view>
                </view>
                <view class="member-info">
                  <text class="member-name">{{ item.nickname }}</text>
                  <text class="member-status completed">{{ item.status || '已完成' }}</text>
                </view>
                <wd-icon name="arrow-right" size="18px" color="#bbb" />
              </view>
              <view class="member-details">
                <view class="detail-item">
                  <wd-icon name="check-circle" size="16px" color="#52c41a" />
                  <text class="detail-text">完成 {{ item.completedBooks }}/{{ item.totalBooks }} 本</text>
                </view>
                <view v-if="item.lastSubmitTime" class="detail-item">
                  <wd-icon name="time" size="16px" color="#1890ff" />
                  <text class="detail-text">{{ formatDateTime(item.lastSubmitTime) }}</text>
                </view>
              </view>
            </view>
          </view>
          <view v-else class="empty-state">
            <!-- <wd-icon name="check-circle" size="48px" color="#52c41a" /> -->
            <!-- <text class="empty-title">太棒了！</text> -->
            <text class="empty-desc">暂无成员完成此作业</text>
          </view>
        </view>

        <view v-if="data.activeTab === 'incompleted'" class="member-list-tab-content">
          <view v-if="data.incompletedInfos.length > 0">
            <view
              v-for="item in data.incompletedInfos"
              :key="item.userId"
              class="member-detail-card"
              @click="() => {}"
            >
              <view class="member-header">
                <view class="avatar-container">
                  <wd-img
                    v-if="item.avatar && !avatarErrors[`incompleted-${item.userId}`]"
                    :src="item.avatar"
                    width="60px"
                    height="60px"
                    shape="circle"
                    custom-class="member-avatar"
                    @error="handleAvatarError(`incompleted-${item.userId}`)"
                  />
                  <view v-else class="member-avatar-placeholder">
                    {{ getAvatarText(item.nickname) }}
                  </view>
                </view>
                <view class="member-info">
                  <text class="member-name">{{ item.nickname }}</text>
                  <text class="member-status" :class="getStatusClass(item.status)">{{ item.status }}</text>
                </view>
                <wd-icon name="arrow-right" size="18px" color="#bbb" />
              </view>
              <view class="member-details">
                <view class="detail-item">
                  <wd-icon name="list" size="16px" color="#52c41a" />
                  <!-- <wd-icon name="book" size="16px" color="#1890ff" /> -->
                  <text class="detail-text">进度 {{ item.completedBooks }}/{{ item.totalBooks }} 本</text>
                  <text class="detail-text">完成度 {{ item.progressPercentage }}%</text>
                </view>
                <view v-if="item.lastSubmitTime" class="detail-item">
                  <wd-icon name="time" size="16px" color="#faad14" />
                  <text class="detail-text">{{ formatDateTime(item.lastSubmitTime) }}</text>
                </view>
                <!-- <view v-if="item.remainingBooks > 0" class="detail-item">
                  <wd-icon name="warning" size="16px" color="#ff4d4f" />
                  <text class="detail-text">还需完成 {{ item.remainingBooks }} 本</text>
                </view> -->
              </view>
            </view>
          </view>
          <view v-else class="empty-state">
            <!-- <wd-icon name="trophy" size="48px" color="#faad14" /> -->
            <wd-icon name="check-circle" size="48px" color="#52c41a" />
            <!-- <text class="empty-title">太棒了！</text> -->
            <text class="empty-title">全部完成！</text>
            <text class="empty-desc">所有成员均已完成此作业</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 内容包装器结束 -->
    </view>
  </view>
</template>

<style lang="scss" scoped>
// 导入公共样式变量
@import '@/styles/variables.scss';

// 动画定义
@keyframes fadeInUp {
  0% {
    opacity: 0;
    transform: translateY(30px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.root-container {
  min-height: 100vh;
  background: $bg-gradient;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: $container-padding 0;

  // 响应式容器宽度
  .content-wrapper {
    width: 100%;
    max-width: 768px; // 最大宽度限制，适合平板和大屏手机
    padding: 0;
    display: flex;
    flex-direction: column;
    gap: $section-margin;

    // 添加进入动画
    animation: fadeInUp 0.6s ease-out;
    transform-origin: center;

    // 当内容不足一屏时，垂直居中
    min-height: calc(100vh - #{$container-padding * 2});
    justify-content: center;

    // 确保内容不会被系统UI遮挡
    padding-bottom: env(safe-area-inset-bottom, 20px);

    // 当内容超过一屏时，允许正常滚动
    @media (max-height: 800px) {
      justify-content: flex-start;
      min-height: auto;
    }

    // 小屏设备优化
    @media (max-width: 480px) {
      max-width: 100%;
      padding: 0 16px;
    }

    // 大屏设备优化
    @media (min-width: 1024px) {
      max-width: 900px;
      padding: 0 32px;
    }

    // 平板设备优化
    @media (min-width: 768px) and (max-width: 1023px) {
      max-width: 720px;
      padding: 0 24px;
    }
  }
}

.assignment-card {
  // 基础样式
  @include glass-effect;
  border-radius: $border-radius-xl;
  padding: 0 ;
  margin: 0 $spacing-md;
  box-shadow: $shadow-lg;

  // 增强视觉效果
  transform: translateZ(0); // 启用硬件加速
  transition: all 0.3s ease;

  // 嵌套规则
  &:hover {
    transform: translateY(-2px) translateZ(0);
    box-shadow: 0 8px 25px rgba(83, 144, 245, 0.15);
  }

  &.custom-class {
    padding: 0;
    margin: 0 $spacing-md;
  }

  .card-content {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    padding: $spacing-lg;
    gap: $spacing-md;
  }

  // 左侧图标区域样式
  .left-icon-area {
    @include center-flex;
    width: 64px;
    height: 64px;
    background: $blue-gradient;
    border-radius: $border-radius-lg;
    box-shadow: $shadow-blue;
    transition: $transition-all;
    flex-shrink: 0;

    &:active {
      transform: scale(0.95);
    }
  }

  .middle-info-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    min-width: 0;

    .assignment-title {
      font-size: $font-size-lg;
      font-weight: $font-weight-semibold;
      color: $dark-gray;
      line-height: $line-height-normal;
      margin-bottom: $spacing-md;
      word-wrap: break-word;
      word-break: break-all;
      white-space: normal;
      overflow-wrap: break-word;
    }

    .assignment-details {
      display: flex;
      flex-direction: column;
      gap: $spacing-sm;

      .detail-row {
        display: flex;
        gap: $spacing-md;
        flex-wrap: wrap;

        @media (max-width: 480px) {
          flex-direction: column;
          gap: $spacing-sm;
        }
      }

      .detail-item {
        display: flex;
        align-items: center;
        gap: 0px;

        .detail-label {
          font-size: $font-size-sm;
          color: $medium-gray;
          font-weight: $font-weight-medium;
          line-height: $line-height-normal;
        }

        .detail-text {
          font-size: $font-size-sm;
          color: $medium-gray;
          font-weight: $font-weight-regular;
          line-height: $line-height-normal;
        }
      }

      .progress-section {
        display: flex;
        flex-direction: column;
        gap: $spacing-sm;

        .progress-info {
          display: flex;
          align-items: center;
          gap: 0px;

          .detail-label {
            font-size: $font-size-sm;
            color: $medium-gray;
            font-weight: $font-weight-medium;
            line-height: $line-height-normal;
          }

          .progress-text {
            font-size: $font-size-sm;
            color: $medium-gray;
            font-weight: $font-weight-regular;
          }
        }

        .progress-bar {
          width: 100%;
          height: 6px;
          background-color: rgba(0, 0, 0, 0.06);
          border-radius: 3px;
          overflow: hidden;

          .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #1890ff 0%, #52c41a 100%);
            border-radius: 3px;
            transition: width 0.3s ease;
            min-width: 2px;
          }
        }
      }
    }

    // 兼容旧样式
    .completion-status {
      font-size: $font-size-sm;
      color: $medium-gray;
      font-weight: $font-weight-medium;
      line-height: $line-height-normal;
    }
  }

  // 右侧操作按钮区域
  .right-actions-area-horizontal {
    display: flex;
    flex-direction: column;
    gap: $spacing-sm;
    align-items: center;
    align-self: flex-start;
    flex-shrink: 0;
  }
}

// Tabs 区域样式
.tabs-container {
  @include glass-effect;
  border-radius: $border-radius-xl;
  overflow: hidden;
  box-shadow: $shadow-lg;
  margin: 0 10px;

  // 自定义 wd-tabs 的一些样式
  :deep(.wd-tabs__nav) {
    background-color: transparent;
  }

  :deep(.wd-tabs__line) {
    background: $blue-gradient;
    height: 3px;
    border-radius: $border-radius-xs;
  }

  :deep(.wd-tab__title--active) {
    color: $primary-blue;
    font-weight: $font-weight-semibold;
  }

  :deep(.wd-tab__title) {
    font-size: $font-size-base;
    font-weight: $font-weight-medium;
    color: $medium-gray;
    transition: $transition-colors;
  }
}

.tab-content {
  background: linear-gradient(135deg, $white-90 0%, $white-80 100%);
  min-height: 400px;
  backdrop-filter: $glass-blur-sm;

  .empty-state {
    @include center-flex;
    flex-direction: column;
    padding: $spacing-3xl;
    min-height: 200px;
    gap: $spacing-md;

    .empty-title {
      font-size: $font-size-xl;
      color: $dark-gray;
      font-weight: $font-weight-bold;
      margin-top: $spacing-sm;
    }

    .empty-desc {
      font-size: $font-size-base;
      color: $medium-gray;
      font-weight: $font-weight-medium;
      text-align: center;
      line-height: $line-height-relaxed;
    }
  }
}

// 作业详情 Tab 内容样式 (绘本列表)
.detail-tab-content {
  padding: $spacing-md;



  // .books-section {
  //   .section-header {
  //     display: flex;
  //     align-items: center;
  //     gap: $spacing-sm;
  //     margin-bottom: $spacing-lg;

  //     .section-title {
  //       font-size: $font-size-lg;
  //       color: $dark-gray;
  //       font-weight: $font-weight-bold;
  //     }
  //   }
  // }

  .books-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: $spacing-lg;

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }
  }

  .book-detail-card {
    background: rgba(255, 255, 255, 0.9);
    border-radius: $border-radius-xl;
    padding: $spacing-lg;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.3);
    transition: $transition-all;
    cursor: pointer;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 20px rgba(83, 144, 245, 0.15);
    }

    &:active {
      transform: translateY(0);
    }

    .book-header {
      margin-bottom: $spacing-md;

      .book-cover-container {
        position: relative;
        width: 100%;
        height: 120px;
        border-radius: $border-radius-lg;
        overflow: hidden;

        .book-cover {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: $border-radius-lg;
        }

        .book-index {
          position: absolute;
          top: $spacing-sm;
          left: $spacing-sm;
          background: $blue-gradient;
          color: $white;
          width: 24px;
          height: 24px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: $font-size-sm;
          font-weight: $font-weight-bold;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }

        .completion-badge {
          position: absolute;
          top: $spacing-sm;
          right: $spacing-sm;
          width: 28px;
          height: 28px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          background: rgba(255, 255, 255, 0.9);
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

          &.completed {
            background: rgba(82, 196, 26, 0.1);
            border: 1px solid #52c41a;
          }
        }

        .completion-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(82, 196, 26, 0.1);
          border-radius: $border-radius-lg;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          gap: $spacing-xs;
          backdrop-filter: blur(2px);

          .completion-text {
            font-size: $font-size-sm;
            color: #52c41a;
            font-weight: $font-weight-bold;
          }
        }
      }
    }

    .book-content {
      .book-title {
        font-size: $font-size-lg;
        color: $dark-gray;
        font-weight: $font-weight-bold;
        line-height: $line-height-tight;
        margin-bottom: $spacing-md;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      .book-meta {
        display: flex;
        flex-direction: column;
        gap: $spacing-sm;
        margin-bottom: $spacing-lg;

        .meta-item {
          display: flex;
          align-items: center;
          gap: $spacing-sm;

          .meta-text {
            font-size: $font-size-sm;
            color: $medium-gray;
            font-weight: $font-weight-medium;

            &.completed {
              color: #52c41a;
            }
          }
        }
      }

      .book-actions {
        display: flex;
        justify-content: center;

        .action-button {
          display: flex;
          align-items: center;
          gap: $spacing-sm;
          padding: $spacing-sm $spacing-lg;
          border-radius: $border-radius-md;
          transition: $transition-all;

          &.primary {
            background: $blue-gradient;
            color: $white;
            box-shadow: 0 2px 8px rgba(83, 144, 245, 0.3);

            &:active {
              transform: scale(0.95);
            }
          }

          .action-text {
            font-size: $font-size-sm;
            font-weight: $font-weight-semibold;
            color: inherit;
          }
        }
      }
    }
  }

  // 兼容旧样式
  .book-item {
    display: flex;
    align-items: center;
    padding: $spacing-lg;
    border-bottom: 1px solid $border-color-light;
    transition: $transition-all;
    cursor: pointer;

    &:last-child {
      border-bottom: none;
    }

    &:active {
      background-color: $white-50;
      transform: scale(0.98);
    }

    .book-cover {
      width: 64px;
      height: 64px;
      border-radius: $border-radius-md;
      margin-right: $spacing-lg;
      background-color: $light-gray;
      flex-shrink: 0;
      box-shadow: $shadow-sm;
    }

    .book-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      min-width: 0;

      .book-title {
        font-size: $font-size-md;
        color: $dark-gray;
        font-weight: $font-weight-medium;
        line-height: $line-height-tight;
        margin-bottom: $spacing-xs;
        @include text-ellipsis;
      }

      .book-status {
        font-size: $font-size-sm;
        color: $medium-gray;
        font-weight: $font-weight-regular;
      }
    }
  }
}

// 编辑弹窗样式
.edit-dialog {
  background: $white;
  border-radius: $border-radius-xl $border-radius-xl 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;

  .dialog-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: $spacing-lg $spacing-lg $spacing-md;
    border-bottom: 1px solid $border-color-light;

    .header-left {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .dialog-title {
      font-size: $font-size-xl;
      font-weight: $font-weight-bold;
      color: $dark-gray;
    }

    .assignment-type-badge {
      font-size: 12px;
      padding: 2px 8px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-radius: 12px;
      font-weight: 500;
    }
  }

  .dialog-content {
    flex: 1;
    padding: $spacing-lg;
    overflow-y: auto;
  }

  .dialog-footer {
    display: flex;
    justify-content: space-between;
    padding: $spacing-lg;
    border-top: 1px solid $border-color-light;

    .cancel-btn,
    .confirm-btn {
      width: 45%;
    }
  }
}

// 表单容器样式
.form-container {
  background: rgba(249, 250, 251, 0.6);
  border-radius: $border-radius-lg;
  padding: $spacing-lg;
  border: 1px solid rgba(229, 231, 235, 0.5);

  .form-item {
    display: flex;
    flex-direction: column;
    margin-bottom: $spacing-lg;

    &:last-child {
      margin-bottom: 0;
    }

    .form-label {
      font-size: $font-size-base;
      color: $dark-gray;
      font-weight: $font-weight-semibold;
      margin-bottom: $spacing-sm;
      display: block;
      line-height: $line-height-normal;
    }

    .form-input {
      flex: 1;
    }
  }
}

// 深度选择器确保表单组件样式
:deep(.form-input) {
  .wd-input {
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: $border-radius-md;
    background: rgba(255, 255, 255, 0.8);

    &:focus-within {
      border-color: #1890ff;
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
    }
  }

  .wd-picker {
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: $border-radius-md;
    background: rgba(255, 255, 255, 0.8);
  }
}

// 成员列表 Tab 内容样式 (已完成/未完成)
.member-list-tab-content {
  padding: $spacing-sm;

  .member-detail-card {
    width: 90%;
    padding: $spacing-lg;
    background: rgba(255, 255, 255, 0.8);
    border-radius: $border-radius-lg;
    margin-bottom: $spacing-md;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    transition: $transition-all;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(83, 144, 245, 0.12);
    }

    &:last-child {
      margin-bottom: 0;
    }

    .member-header {
      display: flex;
      align-items: center;
      gap: $spacing-lg;
      margin-bottom: $spacing-md;

      .member-avatar {
        border-radius: 50% !important;
        box-shadow: 0 2px 8px rgba(83, 144, 245, 0.2);
        border: 2px solid rgba(255, 255, 255, 0.8);
        flex-shrink: 0;
        overflow: hidden;
        width: 60px !important;
        height: 60px !important;
      }

      .member-avatar-placeholder {
        @include center-flex;
        width: 60px;
        height: 60px;
        border-radius: 50% !important;
        background: $blue-gradient;
        color: $white;
        font-size: $font-size-lg;
        font-weight: $font-weight-bold;
        box-shadow: 0 2px 8px rgba(83, 144, 245, 0.3);
        border: 2px solid rgba(255, 255, 255, 0.8);
        flex-shrink: 0;
        overflow: hidden;
      }

      .member-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: $spacing-xs;

        .member-name {
          font-size: $font-size-lg;
          color: $dark-gray;
          font-weight: $font-weight-bold;
          line-height: $line-height-tight;
          letter-spacing: 0.5px;
          text-align: left;
          align-self: flex-start;
        }

        .member-status {
          font-size: $font-size-sm;
          font-weight: $font-weight-semibold;
          padding: 4px 10px;
          border-radius: $border-radius-md;
          display: inline-block;
          width: fit-content;
          text-align: left;
          align-self: flex-start;
          box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

          &.completed {
            color: #389e0d;
            background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
            border: 1px solid #b7eb8f;
          }

          &.in-progress {
            color: #0958d9;
            background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
            border: 1px solid #91d5ff;
          }

          &.not-started {
            color: #cf1322;
            background: linear-gradient(135deg, #fff2f0 0%, #ffccc7 100%);
            border: 1px solid #ffa39e;
          }

          &.unknown {
            color: #595959;
            background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%);
            border: 1px solid #d9d9d9;
          }
        }
      }
    }

    .member-details {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: $spacing-sm;
      padding: $spacing-md;
      background: rgba(249, 250, 251, 0.6);
      border-radius: $border-radius-md;
      border: 1px solid rgba(229, 231, 235, 0.5);

      @media (max-width: 480px) {
        grid-template-columns: 1fr;
      }

      .detail-item {
        display: flex;
        align-items: center;
        gap: $spacing-sm;
        padding: $spacing-xs;
        border-radius: $border-radius-sm;
        background: rgba(255, 255, 255, 0.7);
        transition: $transition-all;

        &:hover {
          background: rgba(255, 255, 255, 0.9);
          transform: scale(1.02);
        }

        .detail-text {
          font-size: $font-size-sm;
          color: $dark-gray;
          font-weight: $font-weight-medium;
          line-height: $line-height-normal;
          letter-spacing: 0.3px;
        }
      }
    }
  }

  // 兼容旧样式
  .member-cell-title {
    display: flex;
    align-items: center;
    gap: $spacing-md;
  }

  .avatar-container {
    position: relative;
    flex-shrink: 0;
  }

  .member-avatar {
    border-radius: $border-radius-full;
    box-shadow: $shadow-sm;
    transition: $transition-all;

    &:hover {
      transform: scale(1.05);
      box-shadow: $shadow-md;
    }
  }

  .member-avatar-placeholder {
    @include center-flex;
    width: $avatar-md;
    height: $avatar-md;
    border-radius: $border-radius-full;
    background: $blue-gradient;
    color: $white;
    font-size: $font-size-lg;
    font-weight: $font-weight-semibold;
    box-shadow: $shadow-blue;
    transition: $transition-all;

    &:hover {
      transform: scale(1.05);
      box-shadow: 0 4px 12px rgba(83, 144, 245, 0.4);
    }
  }

  .member-name {
    font-size: $font-size-md;
    color: $dark-gray;
    font-weight: $font-weight-medium;
    line-height: $line-height-tight;
    text-align: left;
    align-self: flex-start;
  }

  .view-assignment-text {
    font-size: $font-size-sm;
    color: $primary-blue;
    font-weight: $font-weight-medium;
  }
}

// 消息框样式优化
.wd-message-box {
  overflow: hidden;
  border-radius: $border-radius-xl;
  backdrop-filter: $glass-blur;
}

// 确保 wd-card 的 padding 为 0
:deep(.wd-card.assignment-card) {
  padding: 0 !important;
  margin: 0 $spacing-md !important;
}

// 确保头像圆形显示
:deep(.member-avatar) {
  border-radius: 50% !important;
  overflow: hidden !important;

  .avatar-image {
    border-radius: 50% !important;
    width: 44px !important;
    height: 44px !important;
    object-fit: cover !important;
  }
}

// 确保 wd-img 组件内的图片圆形显示
:deep(.wd-img) {
  border-radius: 50% !important;
  overflow: hidden !important;

  .wd-img__image {
    border-radius: 50% !important;
    object-fit: cover !important;
  }
}

// 成员选择器样式
.member-selector {
  background: $white;
  border-radius: $border-radius-lg $border-radius-lg 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.selector-header {
  @include space-between-flex;
  padding: $spacing-lg;
  border-bottom: 1px solid $gray-200;
  background: $white;
  position: sticky;
  top: 0;
  z-index: 10;
}

.selector-title {
  font-size: $font-size-lg;
  font-weight: $font-weight-semibold;
  color: $gray-900;
}

.selector-content {
  flex: 1;
  overflow-y: auto;
  padding: $spacing-md;
}

.select-all-section {
  padding: $spacing-md;
  border-bottom: 1px solid $gray-100;
  margin-bottom: $spacing-md;
}

.members-section {
  display: flex;
  flex-direction: column;
  gap: $spacing-sm;
}

.member-selector-item {
  padding: $spacing-sm;
  border-radius: $border-radius-md;
  border: 1px solid $gray-200;
  background: $white;
  transition: $transition-all;

  &:hover {
    border-color: $blue-300;
    background: rgba(59, 130, 246, 0.05);
  }
}

.member-info {
  @include start-flex;
  gap: $spacing-md;
}

.member-avatar-container {
  flex-shrink: 0;
}

.avatar-placeholder-selector {
  @include center-flex;
  width: 32px;
  height: 32px;
  border-radius: $border-radius-full;
  background: $blue-gradient;
  color: $white;
  font-size: $font-size-sm;
  font-weight: $font-weight-semibold;
}

.member-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
  align-items: flex-start;
}

.member-name {
  font-size: $font-size-md;
  font-weight: $font-weight-medium;
  color: $gray-900;
  text-align: left;
  align-self: flex-start;
}

.member-role {
  font-size: $font-size-sm;
  color: $gray-500;
}

.selector-footer {
  @include space-between-flex;
  padding: $spacing-lg;
  border-top: 1px solid $gray-200;
  background: $white;
  gap: $spacing-md;
}

// 成员预览样式 - 参考创建作业设计
.form-label-row {
  @include space-between-flex;
  align-items: center;
  margin-bottom: $spacing-sm;
}

.member-preview {
  background: rgba(59, 130, 246, 0.05);
  border: 1px solid rgba(59, 130, 246, 0.2);
  border-radius: $border-radius-md;
  padding: $spacing-md;

  .preview-header {
    @include start-flex;
    gap: $spacing-xs;
    margin-bottom: $spacing-md;

    .preview-title {
      font-size: $font-size-sm;
      color: $dark-gray;
      font-weight: $font-weight-semibold;
    }
  }

  .student-container {
    position: relative;

    .student-scroll {
      width: 100%;
      max-height: 180px; // 限制高度，大约显示3行学生
    }

    .student-list {
      display: flex;
      flex-wrap: wrap;
      gap: $spacing-md;
      padding: $spacing-xs 0;

      .student-item {
        flex-shrink: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: $spacing-xs;
        width: 60px; // 固定宽度，确保每行显示固定数量

        .student-avatar {
          .avatar-placeholder {
            @include center-flex;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: $blue-gradient;
            color: $white;
            font-size: $font-size-sm;
            font-weight: $font-weight-bold;
            box-shadow: 0 2px 4px rgba(83, 144, 245, 0.2);
          }
        }

        .student-name {
          font-size: $font-size-xs;
          color: $dark-gray;
          font-weight: $font-weight-medium;
          text-align: center;
          max-width: 60px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }

    .scroll-hint {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: $spacing-xs;
      margin-top: $spacing-sm;
      padding: $spacing-xs;
      background: rgba(153, 153, 153, 0.1);
      border-radius: $border-radius-md;

      .hint-text {
        font-size: $font-size-xs;
        color: #999;
        font-weight: $font-weight-medium;
      }
    }
  }
}

.no-students {
  @include center-flex;
  flex-direction: column;
  gap: $spacing-sm;
  padding: $spacing-lg 0;

  .no-students-text {
    font-size: $font-size-sm;
    color: #ff4d4f;
    font-weight: $font-weight-medium;
    text-align: center;
  }
}

// 编辑对话框中的班级选择器样式
.class-tabs {
  display: flex;
  gap: $spacing-sm;
  margin-bottom: $spacing-md;
  padding: 0 $spacing-xs;
  overflow-x: auto;

  .class-tab {
    flex-shrink: 0;
    padding: $spacing-xs $spacing-sm;
    border-radius: $border-radius-md;
    background: $light-gray;
    border: 1px solid $border-color;
    cursor: pointer;
    transition: all 0.3s ease;

    &.active {
      background: $blue-gradient;
      border-color: $primary-blue;
      color: $white;
    }

    .tab-text {
      font-size: $font-size-sm;
      font-weight: $font-weight-medium;
    }

    .tab-count {
      font-size: $font-size-xs;
      margin-left: $spacing-xs;
      opacity: 0.8;
    }
  }
}

.current-class-students {
  .class-header {
    display: flex;
    justify-content: flex-end;
    margin-bottom: $spacing-sm;
  }

  .student-container {
    width: 100%;

    .student-scroll {
      width: 100%;
      max-height: 200px; // 限制高度，支持滚动
    }

    .student-list {
      display: flex;
      flex-direction: column;
      gap: $spacing-xs;
      padding: $spacing-xs 0;

      .student-item {
        flex-shrink: 0;
        width: 100%;
        margin-bottom: $spacing-sm;
        text-align: left;

        .student-content {
          display: flex !important;
          align-items: center !important;
          justify-content: flex-start !important;
          gap: $spacing-sm;
          width: 100%;
          text-align: left;
          flex-direction: row !important;
        }

        .student-avatar {
          .avatar-placeholder {
            @include center-flex;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: $blue-gradient;
            color: $white;
            font-size: $font-size-sm;
            font-weight: $font-weight-bold;
            box-shadow: 0 2px 4px rgba(83, 144, 245, 0.2);
          }
        }

        .student-name {
          font-size: $font-size-sm;
          color: $dark-gray;
          font-weight: $font-weight-medium;
          flex: 1;
          text-align: left;
        }

        // 确保复选框和内容在一行显示
        :deep(.wd-checkbox) {
          width: 100%;
          display: flex !important;
          align-items: center !important;
          justify-content: flex-start !important;
          text-align: left;
          flex-direction: row !important;

          .wd-checkbox__shape,
          .wd-checkbox__check {
            flex-shrink: 0;
            margin-right: $spacing-sm;
          }

          .wd-checkbox__label {
            width: 100%;
            display: flex !important;
            align-items: center !important;
            text-align: left;
            flex: 1;
            flex-direction: row !important;
          }

          // 确保复选框图标正确显示
          .wd-icon {
            flex-shrink: 0;
          }
        }
      }
    }
  }
}

.member-count {
  font-size: $font-size-xs;
  color: $primary-blue;
  font-weight: $font-weight-medium;
}
</style>
